import moment from "moment";
import SnowflakeId from "snowflake-id";

let UTIL = {
  sleep(time) {
    return new Promise((resolve) => setTimeout(resolve, time))
  },
  getCookie(name) {
    let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)")
    if (arr = document.cookie.match(reg))
      return unescape(arr[2])
    return null
  },
  getBookTagTree() {
    return app.$store.state.tagTree.find(item => item.id == 'e4d0874b39454005afe298541798bebb').children
  },
  axiosUpload(fileObj) {
    let formData = new FormData();
    formData.set("file", fileObj.file);
    app.axios.post(fileObj.action, formData, {
      headers: {
        "Content-type": "multipart/form-data"
      }
    }).then(fileObj.onSuccess).catch()
  },
  generateSfId() {
    // 偏移量与后端保持一致;
    return new SnowflakeId({offset: 1288834974657}).generate()
  },
  recursiveFreeze(obj) {
    Object.freeze(obj)
    for (let prop in obj) {
      if (typeof obj[prop] === 'object') {
        this.recursiveFreeze(obj[prop])
      }
    }
  },
  getObjDefaultEmpty(obj) {
    return obj || {}
  },
  findTreeNode(tree, func) {
    for (const data of tree) {
      if (func(data)) return data
      if (data.children) {
        const res = this.findTreeNode(data.children, func)
        if (res) return res
      }
    }
    return null
  },
  // 递归遍历
  recursiveForEach(data, field, func, postOrderFlag) {
    if (data) {
      if (postOrderFlag) {
        func(data[field], field, func, postOrderFlag)
        func(data)
      }
      else {
        func(data)
        func(data[field], field, func, postOrderFlag)
      }
    }
  },
  // 树 先序遍历
  recursiveForEachTreeNode(tree, func) {
    if (tree) {
      for (const data of tree) {
        func(data)
        this.recursiveForEachTreeNode(data.children, func)
      }
    }
  },
  // 树 后序遍历
  postOrderForEachTreeNode(tree, func) {
    if (tree) {
      for (const data of tree) {
        this.postOrderForEachTreeNode(data.children, func)
        func(data)
      }
    }
  },
  removeTreeNode(tree, node) {
    for (const data of tree) {
      if (data === node) return tree.remove(data)
      if (data.children) {
        this.removeTreeNode(data.children, node)
      }
    }
  },
  isNotEmpty(str) {
    return Boolean(str)
  },
  isEmpty(str){
    return !this.isNotEmpty(str)
  },
  isBlank(str) {
    return this.isEmpty(str) || this.isEmpty(str.trim())
  },
  // 表格, date 列 渲染
  dateFormat: function (row, column, cell) {
    if (cell === undefined) {
      return ''
    }
    return moment(cell).format("YYYY-MM-DD  HH:mm:ss")
  },
  getFileType(fileName) {
    let startIndex = fileName.lastIndexOf('.')
    if (startIndex !== -1) {
      return fileName.slice(startIndex + 1).toLowerCase()
    } else {
      return ''
    }
  },
  // el-upload, 上传文件类型限制, :before-upload或者:on-change绑定的方法
  beforeUpload(file) {
    let suffix = UTIL.getFileType(file.name) //获取文件后缀名
    let suffixArray = ['jpg', 'png', 'jpeg', 'gif', 'tif', 'bmp'] //限制的文件类型，根据情况自己定义
    if (suffixArray.indexOf(suffix) === -1) {
      this.$message({
        message: '文件格式错误',
        type: 'error',
        duration: 2000
      })
      return false
    }
  },
  nonNullObj(obj) {
    return obj !== null && obj !== undefined
  },
  distinctByProp(items, prop) {
    let obj = {}
    // 根据id重复去重
    return items.reduce(function (item, next) {
      obj[next[prop]] ? '' : obj[next[prop]] = true && item.push(next)
      return item
    }, [])
  },
  arrayToStr(arr, prop, joinStr) {
    return arr.map((obj) => {
      return obj[prop]
    }).join(joinStr)
  },
  strToBoolean(obj) {
    return JSON.parse(obj);
  },
  parseCatalogName2KnowledgeUnitName(catalogName) {
    // 去除所有空格;
    let name = catalogName.trim()
    // 去除[]【】
    name = name.replace(/\[?]?【?】?/g, '')
    // 去除开头第一章... 第一节...
    name = name.replace(/^第['一','二','三','四','五','六','七','八','九','十']+['章','节']/, '')
    // 去除开头 一、 二、 三... (一) (二) (三)...
    name = name.replace(/^（?['一','二','三','四','五','六','七','八','九','十']+）?、?/, '')
    // 去除开头 一. 二. 三... (一) (二) (三)...
    name = name.replace(/^（?['1','2','3','4','5','6','7','8','9','0']+）?\.?/, '')
    // 去除结尾:
    name = name.replace(/[':','：']$/, '')
    // 去除开头病例1 病例一 病例2 ...
    name = name.replace(/^病例['一','二','三','四','五','六','七','八','九','十', '0','1','2','3','4','5','6','7','8','9']+/, '')
    // 去除以① ... 开头
    name = name.replace(/^['①','②','③','④','⑤','⑥','⑦','⑧','⑨','⑩']/, '')
    return name.trim()
  },
  isEmptyObj(obj) {
    if (obj) {
      let jsonStr = JSON.stringify(obj)
      return jsonStr === '[]' || jsonStr === '{}'
    }
    return true
  },
  isNotEmptyObj(obj) {
    return !this.isEmptyObj(obj)
  },
  // 判断是否有待处理名称修改意见
  hasUnconfirmedNameSuggestion(nameSuggestion) {
    if (nameSuggestion) {
      return (nameSuggestion.editorNameSuggestion && nameSuggestion.editorStatus === 0)
        || (nameSuggestion.firstAuditorNameSuggestion && nameSuggestion.firstAuditorStatus === 0)
        || (nameSuggestion.secondAuditorNameSuggestion && nameSuggestion.secondAuditorStatus === 0)
        || (nameSuggestion.thirdAuditorNameSuggestion && nameSuggestion.thirdAuditorStatus === 0);
    }
    return false
  },
  emptyFun(){},
  parse2FormData(obj) {
    let formData = new FormData()
    for (let field in obj) {
      if (typeof obj[field] === 'object') {
        formData.append(field, new Blob([JSON.stringify(obj[field])], {type: "application/json"}))
      }
      else {
        formData.append(field, obj[field])
      }
    }
    return formData
  },
  getNameByUserName(userName) {
    if (userName) {
      let filteredUserList = app.$store.state.userList.filter(item => item.userName === userName);
      if (filteredUserList.length > 0) {
        return filteredUserList[0].name
      }
    }
    return ''
  },
  getNameById(array, id) {
    let item = array.find(item => item.id === id);
    if (item) {
      return item.name
    }
    return ''
  },
  //文件下载
  downloadFile(url,fileName){
    let $body = document.body;
    let link = document.createElement('a');
    link.style.display = 'none';
    $body.appendChild(link);
    link.href = url; //创建一个指向该参数对象的url
    link.download = fileName;
    link.click(); // 触发下载
    $body.removeChild(link);
    link = null;
  }

}
UTIL.recursiveFreeze(UTIL)
export default UTIL

